package com.lin.controller;

import cn.hutool.extra.servlet.ServletUtil;
import com.lin.common.RedisCache;
import com.lin.domain.common.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/pvuv")
public class PvUvController {
    @Resource
    private RedisTemplate redisTemplate;
    //redis的pv和uv前缀
    final static String PV_PREFIX = "pv_";
    final static String UV_PREFIX = "uv_";

    /**
     * 统计pv,uv
     * @return 返回统计后的pv,uv值
     */
    @GetMapping()
    public AjaxResult statist(HttpServletRequest request) {
        // 获取yyyy-MM-dd格式的日期
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String today = sdf.format(date);
        String pvKey = PV_PREFIX + today;
        String uvKey = UV_PREFIX + today;
        // pv + 1, incr命令:将 key 中储存的数字值增一。如果 key 不存在，那么 key 的值会先被初始化为 0 ，然后再执行 INCR 操作。
        Long pvNum = redisTemplate.opsForValue().increment(pvKey);
        // hutool获取用户ip
        String clientIP = ServletUtil.getClientIP(request, null);
        // 将ip放到redis的set中
        //redisTemplate.opsForSet().add(uvKey, clientIP); //"SADD myset hello world"
        //Long uvNum = redisTemplate.opsForSet().size(uvKey); // "SCARD myset"
        // 将ip放到redis的HyperLogLog中
        redisTemplate.opsForHyperLogLog().add(uvKey,clientIP); //PFADD mypf ip1 ip2
        Long uvNum = redisTemplate.opsForHyperLogLog().size(uvKey); //PFCOUNT mypf
        AjaxResult ans = AjaxResult.success();
        ans.put("pv",pvNum);
        ans.put("uv",uvNum);
        return ans;
    }
}
